package ru.sgu.acm.judge.misc;

import ru.sgu.acm.misc.Constants;

import java.util.Map;
import java.util.HashMap;

/**
 * This class contains strategy for retrying in case failure.
 *
 * @author Vitaly Goldshteyn (VitalyGoldstein@gmail.com)
 */
public class RetryingStrategy {
    private static Map<String, Long> starts = new HashMap<String, Long>();

    /**
     * Starts retryin section.
     */
    public static void startRetryingSection(String name) {
        starts.put(name, System.currentTimeMillis());
    }

    public static boolean isTryOneMoreTime(String name, long maxPeriod) {
        if (!starts.containsKey(name)) {
            throw new RuntimeException("Can't find retrying section " + name + ".");
        }
        return System.currentTimeMillis() - starts.get(name) <= maxPeriod;
    }

    /**
     * @return is it need to try ones more for last starting retrying section. 
     */
    public static boolean isTryOneMoreTime(String name) {
        return isTryOneMoreTime(name, Constants.getMaximalRetryingTime());
    }
}
